﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using BitwiseOre.SharedMemory.JetBrains;

namespace BitwiseOre.SharedMemory.Core.Primatives
{
    [UsedImplicitly]
    internal sealed class ConnectionBuffersSizer : IConnectionBuffersSizer
    {
        private const int VirtualMemoryFactor = 4;
        private readonly IMemoryStatus _memoryStatus;

        public ConnectionBuffersSizer(IMemoryStatus memoryStatus)
        {
            _memoryStatus = memoryStatus;
        }

        public long Size(int count, int bufferSize)
        {
            return checked(QueueConstants.ConnectionBuffersFixedSize +
                           QueueConstants.ConnectionBuffersVariableSize*count +
                           QueueConstants.ConnectionBuffersBufferSize*count*bufferSize);

        }

        public bool IsSizeInvalid(int count, int bufferSize)
        {
            var variablepartmax = int.MaxValue - QueueConstants.ConnectionBuffersFixedSize;
            var bufferpartmax = (variablepartmax/count) - QueueConstants.ConnectionBuffersVariableSize;
            var buffersizemax = bufferpartmax/QueueConstants.ConnectionBuffersBufferSize;

            return bufferSize > buffersizemax || (ulong) Size(count, bufferSize) > GetMaxMemory();
        }

        private ulong GetMaxMemory()
        {
            return _memoryStatus.GetAvailableVirtualMemory()/VirtualMemoryFactor;
        }
    }
}